﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceWorkerTest
{
    public sealed class FakeHostService : IHostedService
    {
        private readonly IHostApplicationLifetime _lifetime;
        private IDisposable? _tokenSource;
        public FakeHostService(IHostApplicationLifetime lifetime)
        {
            _lifetime = lifetime;
            lifetime.ApplicationStarted.Register(() => Console.WriteLine(
                "[{0}] Application Started", DateTimeOffset.Now));
            lifetime.ApplicationStopping.Register(() => Console.WriteLine(
                "[{0}] Application Stoppting", DateTimeOffset.Now));
            lifetime.ApplicationStopped.Register(() => Console.WriteLine(
                "[{0}] Application Stopted", DateTimeOffset.Now));
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5))
                .Token.Register(_lifetime.StopApplication);

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _tokenSource?.Dispose();
            return Task.CompletedTask;
        }
    }
}
